//
//  MTUtil.m
//  mt_ios
//
//  Created by cherry pu on 17/1/17.
//  Copyright © 2017年 miTing. All rights reserved.
//

#import "MBUtil.h"
#import <CommonCrypto/CommonDigest.h>
#import "MBHTTPResponse.h"

static NSRegularExpression * numberExpression;

@interface MBUtil ()

@property (nonatomic,strong) NSRegularExpression * numberExpression;

@end

@implementation MBUtil

#pragma mark - GCD async
+ (void)runInMainQueue:(void (^)(void))queue{
    dispatch_async(dispatch_get_main_queue(), queue);
}

+ (void)runInGlobalQueue:(void (^)(void))queue{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), queue);
}

+ (void)runAfterSecs:(float)secs block:(void (^)(void))block {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, secs * NSEC_PER_SEC), dispatch_get_main_queue(), block);
}

#pragma mark - 翻转数组
+ (NSArray*)reverseArray:(NSArray*)originArray{
    NSMutableArray* array=[NSMutableArray arrayWithCapacity:[originArray count]];
    NSEnumerator* enumerator=[originArray reverseObjectEnumerator];
    for(id element in enumerator){
        [array addObject:element];
    }
    return array;
}


#pragma mark - 生成与好友的conversationId
+ (NSString *)getConversationIdWithUserId:(NSString *)userId
{
    if(userId){
        return [self md5:userId];
    }else{
        return nil;
    }
}

#pragma mark - 获取当前时间戳
+ (int64_t)getCurrentTimestamp
{
    return (((int64_t)[[NSDate date] timeIntervalSince1970]) + 10) * 1000;
}


#pragma mark - 获取用户年龄
+ (NSInteger)getUserAgeWithInputDateString:(NSString *)dateString andDateFormat:(NSString *)dateFormat
{
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = dateFormat;
    NSDate * inputDate = [dateFormatter dateFromString:dateString];
    
    NSTimeInterval dateDiff = [inputDate timeIntervalSinceNow];
    int age = - trunc(dateDiff / (60 * 60 * 24)) / 365;
    return age;
}

#pragma mark - 缓存清理相关
+(float)folderSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    float folderSize = 0;
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            folderSize +=[self fileSizeAtPath:absolutePath];
        }
        return folderSize;
    }
    return 0;
}

+(float)fileSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size / 1024.0 /1024.0;
    }
    return 0;
}

+(void)clearCache:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        if(childerFiles.count == 0){
            [fileManager removeItemAtPath:path error:nil];
        }
        
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            //存在后缀
            if([absolutePath myContainsString:@"thumb_nail"]){
                continue;
            }
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    [[SDImageCache sharedImageCache] clearMemory];
}

#pragma mark - 加密相关
+ (NSString*)uuid{
    NSString *chars=@"abcdefghijklmnopgrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    assert(chars.length==62);
    int len=(int)chars.length;
    NSMutableString* result=[[NSMutableString alloc] init];
    for(int i=0;i<24;i++){
        int p=arc4random_uniform(len);
        NSRange range=NSMakeRange(p, 1);
        [result appendString:[chars substringWithRange:range]];
    }
    return result;
}


+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (int)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

+ (BOOL)checkStringIsNumWithStr:(NSString *)string
{
    if(numberExpression == nil){
        numberExpression = [[NSRegularExpression alloc]initWithPattern:@"^[0-9]*$" options:NSRegularExpressionCaseInsensitive error:nil];
    }
    
    NSTextCheckingResult * result = [numberExpression firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
    
    if(result){
        return YES;
    }else{
        return NO;
    }
}

#pragma mark - 根据绘画风格获取显示颜色
+ (UIColor *)getColorWithTypeString:(NSString *)string
{
    UIColor * tagColor;
    if([string isEqualToString:@"水彩"]){
        tagColor = [UIColor colorWithHexString:@"43b7a3"];
    }else if([string isEqualToString:@"彩铅"]){
        tagColor = [UIColor colorWithHexString:@"43b748"];
    }else if([string isEqualToString:@"素描"]){
        tagColor = [UIColor colorWithHexString:@"43b748"];
    }else if([string isEqualToString:@"转手绘"]){
        tagColor = [UIColor colorWithHexString:@"5c43b7"];
    }else if([string isEqualToString:@"Q版漫画"]){
        tagColor = [UIColor colorWithHexString:@"b79243"];
    }else if([string isEqualToString:@"日系漫画"]){
        tagColor = [UIColor colorWithHexString:@"4371b7"];
    }else if([string isEqualToString:@"其他"]){
        tagColor = [UIColor colorWithHexString:@"b743ab"];
    }
    return tagColor;
}

#pragma mark - 获取当前控制器
+ (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}


@end
